<?php
namespace app\backend\controller;

use app\backend\model\Lists as ListsModel;
use app\backend\model\Tab as TabModel;
use app\backend\model\Menu as MenuModel;
use app\backend\model\Stage as StageModel;
use think\Request;
use think\Db;
use app\backend\org\Image;

class  Lists  extends Base
{
    //新闻简介列表
    public function index($type,$id=0)
    {
        if($type == "news"){
            $this->assign('jsController','news');
            //模板文件中新闻管理和文章管理的名字
            $this->assign('menu_name','新闻管理');
            $this->assign('xw','新闻');
        }elseif ($type == "articles"){
            $this->assign('jsController','articles');
            $this->assign('menu_name','文章管理');
            $this->assign('xw','文章');
        }

        $type_id = Db::query("select type_id from ls_type where remark_en='$type' and delete_time is null");
        $model = model("Lists");
        //var_dump($model);exit;
        //index页面select内容
        $tab_select = Db::query("select tab_id,tab_name_cn from ls_tab where p_id=$id and delete_time is null and type_id={$type_id[0]['type_id']}");

        //筛选tab_select 查p_id等于tab_id的数据
        $tab_id = Request::instance()->param("tab_id");
        if(!isset($tab_id)){
            $result = $model->getAll($type,$tab_select[0]["tab_id"])->paginate(5, false, ['query' => ['tab_id' => input('tab_id')]]);// ['query' => ['tab_id' => input('tab_id')]]
        }else{
            $result = $model->getAll($type,$tab_id)->paginate(5, false, ['query' => ['tab_id' => input('tab_id')]]);
        }
        $page = $result->render();

        //添加跟修改按钮 已有内容不出现添加按钮
        foreach($result as $k=>$v){
            $stage_p = Db::query("select stage_id,p_id,stage_title_cn,content_cn from ls_stage where `p_id`={$v['list_id']} and delete_time is null ");
            //var_dump($stage_p);exit;
            if(!empty($stage_p)){
                //echo 111 ;exit;
                $result[$k]["flag"] = 1;
                //$this->assign('flag',"1");
            }else{
                $result[$k]["flag"] = 0;
                // echo 555 ;exit;
                //$this->assign('flag',"0");
            }
        }
        //$tab = Db::query("select tab_id,tab_name_cn from ls_tab where p_id=$id and delete_time is null ");
        $this->assign('tab_select',$tab_select);
        $this->assign('tab_id',$tab_id);
        $this->assign('page',$page);
        $this->assign('id',$id);
        $this->assign('type',$type);
        $this->assign('lists',$result);
        $this->assign('empty',"暂无数据");
        return $this->fetch("lists/index");
    }

    //新建新闻简介
    public function lists_create($type="")
    {
        if (Request::instance()->isPost()){
            $model = new ListsModel;
            $post = Request::instance()->post();// 获取经过过滤的全部post变量
//var_dump($post);exit;
            $post["p_id"] = $post["nav-select3"];
            if(isset($post["news_id"])){
                $post["news_id"] = implode(",",$post["news_id"]);
            }
           // var_dump($post);exit;
            if(!$post["news_time"]){
                $post["news_time"]=date("Y-m-d h:i:s");
            }

            //调用图片上传助手类
            if($type=="news"){
                $path = NEWS_PATH;
            }elseif ($type == "articles"){
                $path = PAGE_PATH;
            }
            if(!(Image::image($post,$path))){
                $this->error("图片上传失败");
            }
            //var_dump($post);exit;
            unset($post["img_type"]);
            //var_dump($post);exit;
            // die();
            // 判断已有内容不能重复新增去修改
            $name = Db::query("select list_id,p_id,list_title_cn from ls_list where `p_id`='".$post['p_id']."' and  `list_title_cn`='".$post['list_title_cn']."' and delete_time is NULL ");
            //var_dump($name);exit;
            if(!empty($name)){
                return $this->redirect(url('lists_update',array('list_id'=>$name[0]['list_id'])));
            }
            //手动排序
            $maual_sort = Db::query("select manual_sort from ls_list where p_id='".$post["p_id"]."' and type_id='".$post["type_id"]."' and  delete_time is null");
            if(!empty($maual_sort)){
                //sort函数 排序 [0]最小值
                sort($maual_sort);
                //最大值
                $max = $maual_sort[count($maual_sort)-1];
                $post["manual_sort"]= $max["manual_sort"]+1;
            }else{
                $post["manual_sort"]=1;
            }

             //var_dump( $post["manual_sort"]);exit;

            //置顶插入分类id
            $tab_type = Db::query("select tt_id from ls_tab_type where tab_id='".$post["p_id"]."' and  delete_time is null");
            if($post["type_id"]==1){
                $post["is_recommend"] = "0,{$tab_type[0]['tt_id']}";
            }

           // $recommend = Db::query("update ls_list set `is_recommend`='0,{$tab_type[0]['tt_id']}' where p_id='".$post["p_id"]."' and type_id='".$post["type_id"]."' and  delete_time is null");

            // 验证表单并插入数据库
            $result = $this->validate($post,'Lists.add');
            if(true !== $result){
                // 验证失败 输出错误信息
                dump($result);
                return $this->error($msg = '参数错误，验证失败');
            }

            // 登录人的ID
            $post["creator_id"] = \think\Session::get('login_id');

            unset($post["nav-select3"]);
            unset($post["img-type"]);
            unset($post["menu_id"]);
            unset($post["chose"]);
            //$model->insert($post);
//var_dump($post);exit;
            // 跳转到显示页面
            // 插入数据库后修改数据库跳转连接
            $line = $model->save($post);
            $id = Request::instance()->param("id");
            $type = Request::instance()->param("type");
            //var_dump($model);
            //var_dump($line);die();
            if(!$line){
                return $this->error($this->update_error);
            } else {
//                return $this->redirect('lists/index',["type"=>$type,"id"=>$id,'tab_id'=>$post["p_id"]]);
                return $this->success("新建成功",url('lists/index', ["type"=>$type,"id"=>$id]) . '?tab_id='.$post["p_id"]);
            }
        }
        $type = Request::instance()->param("type");
        if($type == "news"){
            $this->assign('jsController','news');
            $type_id = 1;
        }elseif ($type == "articles"){
            $this->assign('jsController','articles');
            $type_id = 2;
        }

        //查询复选框内容
        $check=TabModel::field('tab_id,tab_name_cn')->where(["delete_time"=>["exp","is null"],"type_id"=>["exp","in($type_id)"]])->select();
        $this->assign('check',$check);
        $this->assign('type_id',$type_id);
        $this->assign('type',$type);
        $id = Request::instance()->param("id");
        $this->assign('id',$id);
        $nav3 = TabModel::field('tab_id,tab_name_cn')->where(['p_id'=>$id,"delete_time"=>["exp","is null"],"type_id"=>["exp","in($type_id)"]])->select();

        $this->assign('nav3',$nav3);
        // $this->assign('act','index');
        //unset($fid);
        return $this->fetch();
    }


    //新闻简介修改
    public function lists_update($list_id)
    {
        if (Request::instance()->isPost())
        {
            $model = new ListsModel;
            $post = Request::instance()->post();// 获取经过过滤的全部post变量
            //调用图片上传助手类
            if(!(Image::image($post,NEWS_PATH))){
                $this->error("图片上传失败");
            }
            if(!$post["news_time"]){
                $post["news_time"]=date("Y-m-d h:i:s");
            }
            //复选框
            if(isset($post["news_id"])){
                $post["news_id"] = implode(",",$post["news_id"]);
            }else{
                //取消选中多选框
                $post["news_id"] = "";
            }
//var_dump($post);exit;
            //验证表单并插入数据库
            $result = $this->validate($post,'Lists.edit');
            if(!$result){
                $this->error($result->getError());
            }
            // 过滤掉数据表中没有的字段，保存
            $result = $model->allowField(true)->save($post,['list_id'=>$list_id]);
            $type = Request::instance()->param("type");
            //var_dump($menu_id);exit;
            //echo $result;exit;
            //$id = Request::instance()->param("id");
            $tab_id = $model->where(["list_id"=>$list_id])->value("p_id");
            $menu_id = Db::query("select p_id from ls_tab where tab_id = $tab_id");
            //var_dump($tab_id);exit;
            if(false === $result){
                $this->error($this->update_error);
            } else {
                $this->success('修改成功',url('lists/index', ["type"=>$type,"id"=>$menu_id[0]["p_id"]]) . '?tab_id='.$tab_id);
            }
        }

        //根据主键插记录
        $record = ListsModel::get($list_id);
        //var_dump($record);exit;
        $type_id = ListsModel::where(["list_id"=>$list_id,"delete_time"=>["exp","is null"]])->value("type_id");
       // $id = Request::instance()->param("id");
        //var_dump($record);exit;
        $type = Request::instance()->param("type");
       // $this->assign('id',$id);
        $this->assign('type',$type);
        $this->assign('lists', $record);
        $this->assign('list_id', $list_id);
        //$this->assign('act','index');
        $news_time = explode(',',$record["news_id"]);
        //查询复选框内容
        $check=TabModel::field('tab_id,tab_name_cn')->where(["delete_time"=>["exp","is null"],"type_id"=>["exp","in($type_id)"]])->select();
        //var_dump($check);exit;
        $this->assign('check',$check);
        //修改复选框内容，除去他本身所在tab，跟之前选中的tab，字符串拼接写法
        $str = "";
        foreach ($check as $k=>$v){
            $str .= '<label class="col-sm-6">
                    <input class="input-release-name" name="news_id[]" type="checkbox" value="'.$v["tab_id"].'"';
            if($record["p_id"] == $v["tab_id"]) {
                $str .= ' disabled';
            }elseif(!empty($news_time) && in_array($v["tab_id"],$news_time)){
                    $str .=  ' checked';
            }
            $str .= '> '.$v["tab_name_cn"].'</label>';




        }
        //新闻 文章页面分配
        $this->assign('type_id',$type_id);
        $this->assign('str', $str);

        return $this->fetch();
    }


    //新闻简介修改
    public function lists_delete($list_id)
    {
        $stage_p = Db::query("select stage_id,p_id,stage_title_cn from ls_stage where `p_id`=$list_id and delete_time is null ");
        if(!empty($stage_p)){
            //$this->error("该简介下有内容，请先删除其内容");
            StageModel::destroy($stage_p[0]["stage_id"]);
            $tab_id = ListsModel::where(["list_id"=>$list_id])->value("p_id");
            $id = TabModel::where(["tab_id"=>$tab_id,"delete_time"=>["exp","is null"]])->value("p_id");
            $type = Request::instance()->param("type");
            ListsModel::destroy($list_id);
            $this->redirect(url('lists/index', ["type"=>$type,"id"=>$id]) . '?tab_id='.$tab_id);
        }else{
            $tab_id = ListsModel::where(["list_id"=>$list_id])->value("p_id");
            $id = TabModel::where(["tab_id"=>$tab_id,"delete_time"=>["exp","is null"]])->value("p_id");
            $type = Request::instance()->param("type");
            ListsModel::destroy($list_id);
            $this->redirect(url('lists/index', ["type"=>$type,"id"=>$id]) . '?tab_id='.$tab_id);
        }

    }

    //homepage置顶
    public function lists_stick($list_id){
        //tab_id
        $tab_id = ListsModel::where(["list_id"=>$list_id,"delete_time"=>["exp","is null"]])->value("p_id");
        //menu_id tab_id的p_Id
        $id = TabModel::where(["tab_id"=>$tab_id,"delete_time"=>["exp","is null"]])->value("p_id");
        //新闻的tab分类
        $tab_type = Db::query("select tt_id,tt_name_cn,tt_name_en from ls_tab_type where tab_id=$tab_id and delete_time is null ");

        $rec ="1,".$tab_type[0]["tt_id"];

        $is_recom = Db::query("select list_id from ls_list where p_id=$tab_id and is_recommend= '".$rec."' and delete_time is null");
        //var_dump($is_recom);exit;
        if(!empty($is_recom)){
            //echo 111;exit;
            ListsModel::update(['is_recommend'=>"0,".$tab_type[0]["tt_id"]],['list_id'=>$is_recom[0]["list_id"]]);
        }
        //var_dump($rec);exit;
        ListsModel::update(['is_recommend'=>$rec],['list_id'=>$list_id]);
        $type = Request::instance()->param("type");
        $this->redirect(url('lists/index', ["type"=>$type,"id"=>$id]) . '?tab_id='.$tab_id);
        return $this->fetch();
    }

    //homepage取消置顶
    public function lists_outstick($list_id){
        $tab_id = ListsModel::where(["list_id"=>$list_id,"delete_time"=>["exp","is null"]])->value("p_id");
        $id = TabModel::where(["tab_id"=>$tab_id,"delete_time"=>["exp","is null"]])->value("p_id");
        $tab_type = Db::query("select tt_id,tt_name_cn,tt_name_en from ls_tab_type where tab_id=$tab_id and delete_time is null ");
        $rec = "0,".$tab_type[0]["tt_id"];
        ListsModel::update(['is_recommend'=>$rec],['list_id'=>$list_id]);
        $type = Request::instance()->param("type");
        $this->redirect(url('lists/index', ["type"=>$type,"id"=>$id]) . '?tab_id='.$tab_id);
        return $this->fetch();
    }

    //list发布功能 list stage两个
    public function is_enable($list_id){
        $type = Request::instance()->param("type");
        if($type=="news"){
            $lists = Db::query("update ls_list set is_enable=1 where delete_time is null and list_id=$list_id   ");
            $stage = Db::query("update ls_stage set is_enable=1  where `p_id`=$list_id and delete_time is null ");
        }
        $tab_id = ListsModel::where(["list_id"=>$list_id,"delete_time"=>["exp","is null"]])->value("p_id");
        $id = TabModel::where(["tab_id"=>$tab_id,"delete_time"=>["exp","is null"]])->value("p_id");
        $this->redirect(url('lists/index', ["type"=>$type,"id"=>$id]) . '?tab_id='.$tab_id);
    }

    public function isnot_enable($list_id){
        $type = Request::instance()->param("type");
        if($type=="news"){
            $lists = Db::query("update ls_list set is_enable=0 where delete_time is null and list_id=$list_id   ");
            $stage = Db::query("update ls_stage set is_enable=0  where `p_id`=$list_id and delete_time is null ");
        }
        $tab_id = ListsModel::where(["list_id"=>$list_id,"delete_time"=>["exp","is null"]])->value("p_id");
        $id = TabModel::where(["tab_id"=>$tab_id,"delete_time"=>["exp","is null"]])->value("p_id");
        $this->redirect(url('lists/index', ["type"=>$type,"id"=>$id]) . '?tab_id='.$tab_id);
    }



}